package com.kamistoat.meimeimall.meimeimallseckill.service.impl;

import com.kamistoat.meimeimall.common.utils.PageUtils;
import com.kamistoat.meimeimall.common.utils.Query;
import com.kamistoat.meimeimall.common.utils.R;
import com.kamistoat.meimeimall.meimeimallseckill.dao.SeckillSkuRelationDao;
import com.kamistoat.meimeimall.meimeimallseckill.entity.SeckillSkuRelationEntity;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.kamistoat.meimeimall.meimeimallseckill.service.SeckillSkuRelationService;
import org.springframework.util.StringUtils;


@Service("seckillSkuRelationService")
public class SeckillSkuRelationServiceImpl extends ServiceImpl<SeckillSkuRelationDao, SeckillSkuRelationEntity> implements SeckillSkuRelationService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SeckillSkuRelationEntity> wrapper = new QueryWrapper<SeckillSkuRelationEntity>();
        String sessionId = (String) params.get("sessionId");
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(sessionId)){
            wrapper.eq("session_id",sessionId);
        }
        IPage<SeckillSkuRelationEntity> page = this.page(
                new Query<SeckillSkuRelationEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 检查当前秒杀中是否以存在相同产品
     * 如果存在，两者只允许备货量不同，其他必须相同
     *
     * @param seckillSkuRelation
     */
    @Override
    public R checkRelation(SeckillSkuRelationEntity seckillSkuRelation) {
        SeckillSkuRelationEntity existOne = baseMapper.selectOne(new QueryWrapper<SeckillSkuRelationEntity>()
                .eq("session_id", seckillSkuRelation.getSessionId())
                .eq("sku_id", seckillSkuRelation.getSkuId()));
        if(existOne == null){
            return R.ok();
        }
        if(!existOne.getSeckillPrice().equals(seckillSkuRelation.getSeckillPrice())){
            return R.error(1, "该商品已存在于本场秒杀中，且秒杀价格不相同");
        }else if(existOne.getSeckillLimit() != seckillSkuRelation.getSeckillLimit()){
            return R.error(1, "该商品已存在于本场秒杀中，且没人限购不相同");
        }else{
            // 合并两个已存在的相同商品
            seckillSkuRelation.setId(existOne.getId());
            seckillSkuRelation.setSeckillCount(seckillSkuRelation.getSeckillCount() + existOne.getSeckillCount());
            seckillSkuRelation.setSeckillSort(Math.min(seckillSkuRelation.getSeckillSort(), existOne.getSeckillSort()));
            R status = new R();
            status.put("data", seckillSkuRelation);
            status.put("code", 2);
            status.put("msg", "已将该商品秒杀库存与已存在的相同商品合并");
            return status;
        }
    }

}